﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WI.CandidateManager.Common.Data.Entities;

namespace WI.CandidateManager.Business.Objects
{
    public class AttachmentBO : BOBase
    {
        public EntityBase GetEntityById(long id)
        {
            try
            {
                EntityBase entity = DataContext.EntityBaseSet.Single(a => a.Id == id);
                if (entity == null)
                    throw new Exception(String.Format("No entity for {0}id!", id));
                return entity;
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                throw ex;
            }
        }
        public List<Attachment> GetAttachmentsListByEntityId(long id)
        {
            try
            {
                EntityBase entity = GetEntityById(id);
                return entity.Attachment.ToList();
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                throw ex;
            }
        }

        public bool SaveAttachment(Attachment attachment)
        {
            try
            {
                DataContext.AttachmentSet.Add(attachment);
                DataContext.SaveChanges();
                Logger.Info(String.Format("{0} added attachment ({1}id)", Session.User, attachment.Id));
                return true;
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                throw ex;
            }
        }

        public Attachment GetAttachmentById(long attachmentId)
        {
            try
            {
                return DataContext.AttachmentSet.Single(a => a.Id == attachmentId);
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                throw ex;
            }
        }

        public bool DeleteAttachment(long attachmentId)
        {
            try
            {
                Attachment attachment = GetAttachmentById(attachmentId);
                DataContext.AttachmentSet.Remove(attachment);
                DataContext.SaveChanges();
                Logger.Info(String.Format("{0} deleted attachment (id-{1}).", Session.User, attachmentId));
                return true;
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
                throw ex;
            }
        }
    }
}
